package mySql

import (
	"math"
	"project/controller"
)

/**
 * @File : getData.go
 * @Description : 将数据库中的数据读入内存
 * @Author : 吴概
 * @Date : 2023/2/8
 */

// GetVideosList 获取视频列表,只获取最后上传的30个视频
func GetVideosList() []controller.Video {
	var video controller.Video
	db.Last(&video)
	l := int(math.Min(30, float64(video.Id)))
	videos := make([]controller.Video, l)
	j := 0
	for i := video.Id; i > 0 && i > video.Id-30; i-- {
		db.First(&videos[j], i)
		videos[j].Author = GetUser(videos[j].AuthorId)
		j++
	}
	return videos
}

// GetVideoListByIdList 根据Id列表返回视频列表
// 由于视频数量巨大，所以需要使用id列表才能快速查找主键
func GetVideoListByIdList(idList []int64) []controller.Video {
	if len(idList) == 0 {
		return nil
	}
	list := make([]controller.Video, len(idList))
	for k, v := range idList {
		db.First(&list[k], v)
	}
	return list
}

// GetUserList 获取账号列表
func GetUserList() (users []controller.User) {
	db.Find(&users)
	return users
}

func GetUserListByIdList(idList []int64) []controller.User {
	if len(idList) == 0 {
		return nil
	}
	res := make([]controller.User, len(idList))
	for k, v := range idList {
		db.First(&res[k], v)
	}
	return res
}

func GetMessageList(chat controller.Chat) []controller.Message {
	idList := controller.GetIdList(chat.MessageIdList)
	if len(idList) == 0 {
		return nil
	}
	res := make([]controller.Message, len(idList))
	for k, v := range idList {
		db.First(&res[k], v)
	}
	return res
}

// GetUserByToken 查询账号user，根据token查询
func GetUserByToken(token string) (res controller.User) {
	db.Where("token = ?", token).First(&res)
	return res
}

func GetUser(id int64) (res controller.User) {
	db.First(&res, id)
	return res
}

// GetDefaultUserName 获取默认用户名，用于注册账号时使用
func GetDefaultUserName() string {
	var temp controller.User
	db.Last(&temp)
	return "用户" + controller.ToString(temp.Id+1)
}

func GetVideoById(id int64) (res controller.Video) {
	db.First(&res, id)
	return res
}

func GetLastVideoId() int64 {
	var video controller.Video
	db.Last(&video)
	return video.Id
}

func GetComment(commentId int64) (res controller.Comment) {
	db.First(&res, commentId)
	return res
}

func GetCommentList(videoId int64) (res []controller.Comment) {
	db.Where("video_id = ?", videoId).Find(&res)
	return res
}

func GetRelation(id int64) (res controller.Relation) {
	db.First(&res, id)
	return res
}

func GetPublish(id int64) (res controller.Publish) {
	db.First(&res, id)
	return res
}

func GetChat(a, b int64) controller.Chat {
	var mark string
	if a > b {
		mark = controller.ToString(a) + ":" + controller.ToString(b)
	} else {
		mark = controller.ToString(b) + ":" + controller.ToString(a)
	}
	var chat controller.Chat
	db.Where("mark = ?", mark).Find(&chat)
	if chat.Id == 0 {
		NewChat(mark)
		return GetChat(a, b)
	}
	return chat
}

// 用户 id
// 获取喜欢结构体
func GetLike(id int64) (res controller.Like) {
	// 找到用户的 Like 结构体
	db.First(&res, id)
	return res
}
